import {
  AppstoreAddOutlined,
  DashboardOutlined,
  PoweroffOutlined,
  ProfileOutlined,
  RightOutlined,
  SettingOutlined,
  ShopOutlined,
  TagOutlined,
} from "@ant-design/icons"
import { security, store } from "@mall/api-services"
import { Avatar, ConfigProvider, Layout, List, Menu, Popover } from "antd"
import zhCN from "antd/es/locale/zh_CN"
import classNames from "classnames"
import "dayjs/locale/zh-cn"
import * as _ from "lodash"
import * as React from "react"
import { lazy, Suspense, useEffect, useState } from "react"
import { BrowserRouter, Link, Redirect, Route, Switch, useHistory, useParams } from "react-router-dom"
import "./App.css"
import classes from "./App.module.scss"
import PrivateRoute from "./components/access"
import Login from "./pages/login"

const Store = store.Store
const StoreServiceV1 = store.StoreServiceV1

interface StoreHeaderProps {
  collapsed: boolean
}

function StoreHeader({ collapsed }: StoreHeaderProps) {
  const history = useHistory()
  const { storeId = "" } = useParams()
  const [store, setStore] = useState(new Store())
  useEffect(() => {
    StoreServiceV1.getStore(storeId).then(setStore)
  }, [storeId])

  const popoverContent = (
    <List itemLayout="horizontal">
      <List.Item onClick={() => history.push(`/stores/${storeId}/dashboard`)}>店铺概况</List.Item>
      <List.Item onClick={() => history.push(`/stores`)}>切换店铺</List.Item>
      <List.Item>
        访问店铺
        <span className={classes.listItemSecondaryText}>{store.name}<RightOutlined/></span>
      </List.Item>
      <List.Item>管理账号
        <span className={classes.listItemSecondaryText}><RightOutlined/></span>
      </List.Item>
      <List.Item onClick={() => {
        security.SecurityUserHolder.logout()
        history.replace("/")
      }}>退出登录<PoweroffOutlined/></List.Item>
    </List>
  )

  return (
    <Popover placement="bottomLeft"
             overlayClassName={classes.storeHeaderMenus}
             content={popoverContent}
             trigger="click"
             align={{ offset: [20, 0] }}>
      <div className={classNames(classes.storeHeader, {
        [classes.storeHeaderCollapsed]: collapsed,
      })}>
        <Avatar src={store.logo} icon={<ShopOutlined/>}/>
        {!collapsed && <span>{store.name}</span>}
      </div>
    </Popover>
  )
}

interface NavMenusProps {
  collapsed: boolean
}

function NavMenus({ collapsed }: NavMenusProps) {
  const history = useHistory()
  const { storeId } = useParams()
  return (
    <div className={classes.navMenus}>
      <div className={classes.mainMenus}>
        <Menu
          theme="dark"
          mode="inline">
          <Menu.Item key="dashboard"
                     onClick={() => history.push(`/stores/${storeId}/dashboard`)}>
            <DashboardOutlined/>
            <span>概况</span>
          </Menu.Item>
          <Menu.SubMenu
            key="store"
            title={<><ShopOutlined/><span>店铺</span></>}>
            <Menu.Item key="attachments">
              <Link to={`/stores/${storeId}/blobs`}>素材空间</Link>
            </Menu.Item>
          </Menu.SubMenu>
          <Menu.SubMenu
            title={<><TagOutlined/><span>商品</span></>}>
            <Menu.Item key="products">
              <Link to={`/stores/${storeId}/products`}>商品管理</Link>
            </Menu.Item>
            <Menu.Item key="custom-collections">
              <Link to={`/stores/${storeId}/custom-collections`}>商品集合</Link></Menu.Item>
          </Menu.SubMenu>
          <Menu.SubMenu
            title={<><ProfileOutlined/><span>订单</span></>}>
            <Menu.Item key="orders">
              <Link to={`/stores/${storeId}/orders`}>订单管理</Link></Menu.Item>
            {/*<Menu.Item key="shipping-rates">
              <Link to={`/stores/${storeId}/shipping-rates`}>物流发货</Link>
            </Menu.Item>*/}
          </Menu.SubMenu>
        </Menu>
      </div>
      <Menu
        theme="dark"
        mode="vertical"
        selectable={false}
        className={classes.fixedMenus}>
        <Menu.Item key="addApp">
          <AppstoreAddOutlined/>
          <span>应用</span>
        </Menu.Item>
        <Menu.SubMenu title={<><SettingOutlined/><span>设置</span></>}>
          <Menu.Item>
            <Link to={`/stores/${storeId}/settings/store-info`}>店铺信息</Link></Menu.Item>
        </Menu.SubMenu>
      </Menu>
    </div>
  )
}


const routes = [{
  exact: true,
  path: "/stores/:storeId/dashboard",
  component: lazy(() => import("./pages/dashboard")),
}, {
  exact: true,
  path: "/stores/:storeId/custom-collections",
  component: lazy(() => import("./pages/collection/custom-collection-list")),
}, {
  exact: true,
  path: "/stores/:storeId/blobs",
  component: lazy(() => import("./pages/store/blobs")),
}, {
  exact: true,
  path: "/stores/:storeId/products/new",
  component: lazy(() => import("./pages/product/new-product")),
}, {
  exact: true,
  path: "/stores/:storeId/products/:productId",
  component: lazy(() => import("./pages/product/edit-product")),
}, {
  exact: true,
  path: "/stores/:storeId/products",
  component: lazy(() => import("./pages/product/product-list")),
}, {
  exact: true,
  path: "/stores/:storeId/orders",
  component: lazy(() => import("./pages/order/order-list")),
}, {
  exact: true,
  path: "/stores/:storeId/orders/:orderId",
  component: lazy(() => import("./pages/order/order-detail")),
}, {
  exact: true,
  path: "/stores/:storeId/settings/store-info",
  component: lazy(() => import("./pages/settings/store-info")),
}, {
  exact: true,
  path: "/stores/:storeId/settings/store-info/edit",
  component: lazy(() => import("./pages/settings/store-info/edit")),
}, {
  exact: true,
  path: "/stores/:storeId/shipping-rates",
  component: lazy(() => import("./pages/shipping/shipping-rate-list")),
}, {
  exact: true,
  path: "/stores/:storeId/shipping-rates/new",
  component: lazy(() => import("./pages/shipping/new-shipping-rate")),
}]

function BaseLayout() {
  const { Content, Sider } = Layout
  const [collapsed, setCollapsed] = useState(true)

  return (
    <Layout className="site-layout">
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <StoreHeader collapsed={collapsed}/>
        <NavMenus collapsed={collapsed}/>
      </Sider>
      <Content>
        <Suspense fallback={<div>loading</div>}>
          <Switch>
            {_.map(routes, route => <PrivateRoute key={route.path} exact={route.exact} path={route.path} component={route.component}/>)}
          </Switch>
        </Suspense>
      </Content>
    </Layout>
  )
}

function App() {
  return (
    <ConfigProvider locale={zhCN}>
      <BrowserRouter>
        <Suspense fallback={<div>loading</div>}>
          <Switch>
            <Route exact path="/login" component={Login}/>
            <Redirect exact path="/" to="/stores"/>
            <PrivateRoute exact path="/logout" component={lazy(() => import("./pages/logout"))}/>
            <PrivateRoute exact path="/stores" component={lazy(() => import("./pages/store/store-list"))}/>
            <PrivateRoute exact path="/stores/create" component={lazy(() => import("./pages/store/create-store"))}/>
            <PrivateRoute exact path="/users/:userId/personal" component={lazy(() => import("./pages/user/personal"))}/>
            <PrivateRoute path="/stores/:storeId" component={BaseLayout}/>
          </Switch>
        </Suspense>
      </BrowserRouter>
    </ConfigProvider>
  )
}

export default App
